package com.metamech.vorpal.handler;

import java.io.Writer;
import java.util.Iterator;

import org.apache.log4j.Logger;

import com.metamech.jabber.JabberID;
import com.metamech.jabber.Session;
import com.metamech.jabber.xml.Packet;
import com.metamech.jabber.xml.PacketListener;
import com.metamech.log.Log;
import com.metamech.vorpal.GroupChatManager;
import com.metamech.vorpal.Server;
import com.metamech.vorpal.User;
import com.metamech.vorpal.UserIndex;

import edu.mobbuzz.web.facade.TrafficFacade;

public class MessageHandler implements PacketListener {
	private static Logger logger=Logger.getLogger(MessageHandler.class);
	/*static SessionIndex sessionIndex;
	GroupChatManager chatMan = GroupChatManager.getManager();
	public MessageHandler(SessionIndex index) { 
		sessionIndex = index; 
	}*/ 
	private static TrafficFacade trafficFacade;
	
	static UserIndex userIndex;
	GroupChatManager chatMan = GroupChatManager.getManager();
	public MessageHandler(UserIndex index) { 
		userIndex = index; 
	}

	public void notify(Packet packet){
		String recipient = packet.getTo();

		if (recipient == null){ // to server
			logger.info("Dropping packet: " + packet.toString());
			return;
		}

		if (recipient.equalsIgnoreCase(Server.SERVER_NAME)){ // to server
			logger.info("Dropping packet: " + packet.toString());
			return;
		}

		// Fill in sender as resource that sent message (anti-spoofing)
		packet.setFrom(packet.getSession().getJID().toString());

		/*if (packet.getAttribute("type").equals("groupchat")){
			if (chatMan.isChatPacket(packet)){
				chatMan.handleChatMessage(packet);
			} else {
				Log.trace("Dropping packet: " + packet.toString());
			}
			return;
		}*/
		deliverPacket(packet);
	}
	
	static public void deliverPacketToAll(String username, Packet packet){
	    packet.setTo(null); // clear recipient
	    User user = userIndex.getUser(username);
	    Iterator sessions = user.getSessions();
	    while (sessions.hasNext()){
	    	Session session = (Session)sessions.next();
	      	if (session.getPriority() >= 0){
	      		packet.setSession(session);
	      		deliverPacket(packet);
	      	}
	    }
	}

	static public void deliverPacket(Packet packet){
		try {
			String recipient = packet.getTo();
			Writer out;
			String body="";
			if (recipient == null){
				out = packet.getSession().getWriter();
				if (out == null){
					logger.info("Undeliverable packet " + packet.toString());
					return;
				}
			} else {
				out = userIndex.getWriter(recipient);
			}
			if (out != null){
				logger.info("Delivering packet: " + packet.toString());
				logger.info("packet from : " + packet.getFrom());
				logger.info("packet to : " + packet.getTo());
				logger.info("packet element : " + packet.getElement());
				if(packet.getElement().equals("message")){
					body = packet.getChildValue("body");
					if(body.equals(""))
						body = packet.toString();					
					getTrafficFacade().addTraffic(packet.getFrom(),packet.getTo(),body);
				}
				logger.trace("kirim");
				packet.writeXML(out);
			} else {
				logger.info("Store & forward: " + packet.toString());
				User user = userIndex.getUser(new JabberID(recipient).getUser());
				user.storeMessage(packet);
			}
		} catch (Exception ex){
			logger.error("MessageHandler: ", ex);
		}
	}

	static public TrafficFacade getTrafficFacade() {
		if(trafficFacade==null)
			trafficFacade = new TrafficFacade();
		return trafficFacade;
	}
	
	
	/*static public void deliverPacket(Packet packet){
		try {
			Session session = sessionIndex.getSession(packet.getTo());
			if (session != null){
				packet.writeXML(session.getWriter());
			} else {
				Log.info("Dropping packet (not home) " + packet.toString());
				return;
			}
		} catch (Exception ex){
			Log.error("MessageHandler: ", ex);
		}
	}*/
}